import { AccountService } from './account.service';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/toPromise';
import { CoolSessionStorage } from './utils/storage/cool-session-storage';
import { HttpServices } from './utils/http.service';
import { environment } from './../../../environments/environment';

export class TokenModel {
      public access_token: string;
      public expires_in: number;
      public refresh_token: string;
      public token_type: string;
      //是否过期
}

export class LoginModel { 
      public name: string;
      public password: string;
}

@Injectable()
 
export class AuthTokenService {

      private tokenUrl: any = environment.tokenApi;

      private token: TokenModel;

      private tokenSessionKey: string = "token";

      private loginRoute: string[] = ['/login'];

      constructor(
            private http: HttpServices,
            private Router: Router,
            private session: CoolSessionStorage,
            // private accountService:AccountService
      ) {
            this.token = this.session.getObject("token") as TokenModel;
      }

      //获取token
      getToken(): TokenModel {
            // alert('constToken');
            return this.token;
      }

      login(data: LoginModel) {
            this.removeToken();
            return this.tokenApi(data);
      }

      logout() {
            this.removeToken();
            this.Router.navigate(this.loginRoute);
      }

      private removeToken() {
            this.token = null;
            this.session.removeItem(this.tokenSessionKey);
      }

      private tokenApi(req:LoginModel): Promise<boolean> {
            // alert('tokenApi');
            let reqData = 'client_id=FLM.Admin.WebClient&client_secret=&grant_type=password&username=' + req.name + '&password=' + req.password;

            return this.http.postForm(this.tokenUrl, reqData)
                  .toPromise()
                  .then(res => {
                        //token->内存
                        this.token = res;
                        //token->本地缓存
                        this.session.setObject(this.tokenSessionKey, this.token);
                        return Promise.resolve(true);
                  })
                  .catch(error => {
                        return Promise.reject(error);
                  });
      }




}